import FlagImage from '@/components/FlagImage';
import * as c from '@/services/consts';
import * as api from '@/services/vpnServerMonitor';
import * as utils from '@/utils/utils';
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  CaretDownOutlined,
  CaretUpOutlined,
  CheckCircleFilled,
  CloseCircleFilled,
  UserOutlined,
} from '@ant-design/icons';
import { CheckCard, PageContainer,  ProCard, ProForm,  ProFormDateTimeRangePicker, ProFormSelect, ProFormTreeSelect } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';

import { Badge,   Radio, Space, Tag, Button, Spin, Collapse } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import LineChart from '@/components/LineChart2';
import dayjs from 'dayjs';
import Countdown from 'antd/es/statistic/Countdown';
const { Panel } = Collapse;

const dateFormat = 'YYYY-MM-DD HH:mm:ss';



export const ChartCard: React.FC<{
  // datas: API.TrafficMonitorItem[] | undefined;
  datas: API.TrafficMonitorData | undefined;
}> = (props) => {
  const{datas } = props;

  

const textAlert = (num: number | string | undefined, max: number | undefined) => {
  if(max && num && Number(num) >= max){
    return <span style={{color:'red', backgroundColor:'yellow'}}>{num}</span>;
  }
  
  return num;
};
  
  let bandwidthTotal = (datas?.bandwidthTotal ?? 0) * 1024 * 1024;

  return <>
    {datas?.recvMaxCount ? 
      <div style={{color:'#888',fontSize:12}}>
        <div>
          <ArrowUpOutlined style={{color:'red'}} />
          <span style={{color:'orange',fontWeight:'bolder'}}>{utils.formatRate(datas?.tranLast, true)}</span>
          {datas?.tranLast > datas?.tranLast2 ? <CaretUpOutlined style={{color:'red'}} />
          : datas?.tranLast < datas?.tranLast2 ? <CaretDownOutlined style={{color:'green'}} /> : ''}
          {datas?.tranLast > 0 && bandwidthTotal > 0 ? <span style={{color:'#666',fontWeight:'bolder'}}>{textAlert(utils.formatPercentage(datas.tranLast / bandwidthTotal, 1), 80)}%</span> : ''}

          [{utils.formatRate(datas?.tranMinCount, true)}
          {datas?.tranMinCount > 0 && bandwidthTotal > 0 ? <span>/{utils.formatPercentage(datas.tranMinCount / bandwidthTotal, 1)}%</span> : ''}&nbsp;&nbsp;&nbsp;
          {utils.formatRate(datas?.tranMaxCount, true)}
          {datas?.tranMaxCount > 0 && bandwidthTotal > 0 ? <span>/{utils.formatPercentage(datas.tranMaxCount / bandwidthTotal, 1)}%</span> : ''}&nbsp;&nbsp;&nbsp;
          {utils.formatRate(datas?.tranMeanCount, true)}
          {datas?.tranMeanCount > 0 && bandwidthTotal > 0 ? <span>/{utils.formatPercentage(datas.tranMeanCount / bandwidthTotal, 1)}%</span> : ''}]&nbsp;
        </div>
        <div>
          <ArrowDownOutlined style={{color:'red'}} />
          <span style={{color:'orange',fontWeight:'bolder'}}>{utils.formatRate(datas?.recvLast, true)}</span>
          {datas?.recvLast > datas?.recvLast2 ? <CaretUpOutlined style={{color:'red'}} />
          : datas?.recvLast < datas?.recvLast2 ? <CaretDownOutlined style={{color:'green'}} /> : ''}
          {datas?.recvLast > 0 && bandwidthTotal > 0 ? <span style={{color:'#666',fontWeight:'bolder'}}>{textAlert(utils.formatPercentage(datas.recvLast / bandwidthTotal, 1), 80)}%</span> : ''}

          [{utils.formatRate(datas?.recvMinCount, true)}
          {datas?.recvMinCount > 0 && bandwidthTotal > 0 ? <span>/{utils.formatPercentage(datas.recvMinCount / bandwidthTotal, 1)}%</span> : ''}&nbsp;&nbsp;&nbsp;
          {utils.formatRate(datas?.recvMaxCount, true)}
          {datas?.recvMaxCount > 0 && bandwidthTotal > 0 ? <span>/{utils.formatPercentage(datas.recvMaxCount / bandwidthTotal, 1)}%</span> : ''}&nbsp;&nbsp;&nbsp;
          {utils.formatRate(datas?.recvMeanCount, true)}
          {datas?.recvMeanCount > 0 && bandwidthTotal > 0 ? <span>/{utils.formatPercentage(datas.recvMeanCount / bandwidthTotal, 1)}%</span> : ''}]
        </div>
      </div>:''}

      {datas?.recvMaxCount1d ? 
      <div style={{color:'#888', fontSize:12}}><>
        <ArrowUpOutlined style={{color:'black'}} />
          <span style={{color:'#666',fontWeight:'bolder'}}>{utils.formatRate(datas?.tranLast1d, true)}</span>
          [{utils.formatRate(datas?.tranMinCount1d, true)}&nbsp;&nbsp;
          {utils.formatRate(datas?.tranMaxCount1d, true)}&nbsp;&nbsp;
          {utils.formatRate(datas?.tranMeanCount1d, true)}]&nbsp;
        <ArrowDownOutlined style={{color:'black'}} />
          <span style={{color:'#666',fontWeight:'bolder'}}>{utils.formatRate(datas?.recvLast1d, true)}</span>
          [{utils.formatRate(datas?.recvMinCount1d, true)}&nbsp;&nbsp;
          {utils.formatRate(datas?.recvMaxCount1d, true)}&nbsp;&nbsp;
          {utils.formatRate(datas?.recvMeanCount1d, true)}]
          &nbsp;1d
        </>
      </div>:''}
                
    <div>
      <LineChart
        data={
          datas?.data?.map((val)=>{
            return val.title?.includes('用户') ? '' :{
          date: val.date,// dayjs(new Date(val.ticks * 1000)).format(dateFormat), //new Date(val.ticks * 1000),//val.ticks,//
          count: utils.formatRateMb(val.count, true), 
          title:`${val.title}M`
        }}) ?? []
        }
        xfield="date"
        yfield="count"
        seriesField="title"
        height={150}
        lineWidth={1}
        displayLabel={undefined}
        displayPoint={false}
        backColor={undefined}//#E6F3FF
        lineColors={['#5B8FF9', '#5AD8A6', '#FA6400', '#E0B400']}
        // lineColors={['#5B8FF9', '#5AD8A6', '#5D7092','#FA6400', '#E0B400','#d4f616']}
      />
    </div>

    
    {datas?.userCountMax ? 
      <div style={{color:'#888',fontSize:12,marginTop:10}}>
          {datas?.userCountMax ?
            <><UserOutlined style={{color:'red'}} />
            <span style={{color:'orange',fontWeight:'bolder'}}>{datas?.userCountLast}</span>
          {datas?.userCountLast > datas?.userCountLast2 ? <CaretUpOutlined style={{color:'red'}} />
          : datas?.userCountLast < datas?.userCountLast2 ? <CaretDownOutlined style={{color:'green'}} /> : ''}
              [{datas?.userCountMin}&nbsp;
              {datas?.userCountMax}&nbsp;
              {datas?.userCountMean}]&nbsp;&nbsp;
            </>:''}

          {datas?.userCountMax1d ?
          <><UserOutlined style={{color:'black'}} />
          <span style={{color:'#666',fontWeight:'bolder'}}>{datas?.userCountLast1d}</span>
            [{datas?.userCountMin1d}&nbsp;
            {datas?.userCountMax1d}&nbsp;
            {datas?.userCountMean1d}]
          </>:''}
          &nbsp;1d
      </div>:''}

    
    <div>
      <LineChart
        data={
          datas?.data?.map((val)=>{
            return val.title?.includes('用户') ? {
          date: val.date,//dayjs(new Date(val.ticks * 1000)).format(dateFormat), //new Date(val.ticks * 1000),//val.ticks,//
          count: val.count, 
          title:`${val.title}`} : ''}) ?? []
        }
        xfield="date"
        yfield="count"
        seriesField="title"
        height={100}
        lineWidth={1}
        displayLabel={undefined}
        displayPoint={false}
        backColor={undefined}//#E6F3FF
        lineColors={['#5B8FF9', '#5AD8A6', '#FA6400', '#E0B400']}
        // lineColors={['#5B8FF9', '#5AD8A6', '#5D7092','#FA6400', '#E0B400','#d4f616']}
      />
    </div>

    {datas?.remark ? 
      <div style={{color:'#999',fontSize:11,marginTop:10}}>{datas.remark}</div> : ''}
  </>;
};





const VpnGroupTreeList: React.FC = (props: any) => {
  const formRef = useRef<ProFormInstance>();
  const [monitorDatas, setMonitorDatas] = useState<API.TrafficMonitorData[] | undefined>(undefined);
  const [countdownTicks, setCountdownTicks] = useState<number>(-1);
  const [controlState, setControlState] = useState<number>(0);
  const [dataLoading, setDataLoading] = useState<boolean>(true);
  const [refreshDataLoading, setRefreshDataLoading] = useState<boolean>(false);
  const [searchType, setSearchType] = useState<number>(1);
  const [searchPoint, setSearchPoint] = useState<number>(50);
  const [searchStart, setSearchStart] = useState<number|undefined>(undefined);
  const [searchEnd, setSearchEnd] = useState<number|undefined>(undefined);
  const [searchHour, setSearchHour] = useState<number>(24);
  const [searchMemberLevel, setSearchMemberLevel] = useState<number|undefined>(-1);
  const [searchGroupIds, setSearchGroupIds] = useState<string[]|undefined>(undefined);
  const [searchAreaPolicy, setSearchAreaPolicy] = useState<string|undefined>(undefined);
  
  // const [productId, setProductId] = useState<string | undefined>(undefined); 
  // const productMenuItems = getProductMenuItems(true); 

  const {getVpnGroupExTrees, globalGrafanaModel
  } = useModel('useGlobalModel', (model) => ({
    // getVpnGroupList: model.getVpnGroupList,
    // suppliers: model.suppliers,
    getVpnGroupExTrees: model.getVpnGroupExTrees,
    globalGrafanaModel: model.globalGrafanaModel,
  }));

  const loadData = async () => {
    const result = await api.trafficMonitorList({
      type: searchType, 
      point: searchPoint, 
      startTicks: searchStart, 
      endTicks: searchEnd,
      hour: searchHour,
      memberLevel: searchMemberLevel,
      groupIds: searchGroupIds,
      areaPolicy: searchAreaPolicy,
    });

    if (result && result.success) {
      setMonitorDatas(result.data);
    } else {
      setMonitorDatas(undefined);
    }
    setCountdownTicks(Date.now() + 60000);
    setDataLoading(false);
    setRefreshDataLoading(false);
  };

  useEffect(() => {
    loadData();
  }, [ controlState ]);  

  const reload = () => {
    if (countdownTicks > 0) {
      setControlState(new Date().getTime());
      setRefreshDataLoading(true);
      // setCountdownTicks(Date.now() + 60000);
    }
  };
 
  
  const loadGroupTreeData = async (params: any) => {
    const treeData = getVpnGroupExTrees(params?.productId);

    return Promise.resolve(treeData);
  };

  // const getGroup = (groupId: string) => {
  //   for(let d of getVpnGroupList()){
  //     if(d.id == groupId) return d;
  //   }
  //   return undefined;
  // }

  // const getSupplier = (code: string) => {
  //   for(let d of suppliers){
  //     if(d.code == code) return d;
  //   }
  //   return undefined;
  // }

  

  return (
    <PageContainer>
      <ProCard loading={dataLoading} gutter={0} title={<>
      <ProForm formRef={formRef} layout='horizontal' submitter={false} style={{width:'100%'}}>
      <div>
        <Space>
          <Radio.Group
            defaultValue={
              searchType == 1 ? 'b' : searchType ==  2 ? 'c' : 'd'
            }
          >
            <Radio
              value="b"
              onClick={() => {
                setSearchType(1);
              }}
            >
              按分组
            </Radio>
            <Radio
              value="c"
              onClick={() => {
                setSearchType(2);
              }}
            >
              按供应商
            </Radio>
            <Radio
              value="d"
              onClick={() => {
                setSearchType(3);
              }}
            >
              按会员级别
            </Radio>
          </Radio.Group>
        </Space>

        <Space style={{marginLeft:30}}>
          <ProFormSelect
            name="point"
            label="取样数"
            allowClear={true}
            initialValue={searchPoint}
            options={[
              {label:'20', value: 20},
              {label:'50', value: 50},
              {label:'100', value: 100},
              {label:'200', value: 200},
            ]}
            fieldProps={{
              onChange(value, option) {
                setSearchPoint(value);
              },
            }}
          />
        </Space>

        <Space style={{marginLeft:10}}>
          <ProFormSelect
            name="hour"
            label="时间区间"
            allowClear={true}
            initialValue={searchHour}
            options={[
              {label:'1小时', value: 1},
              {label:'2小时', value: 2},
              {label:'3小时', value: 3},
              {label:'6小时', value: 6},
              {label:'12小时', value: 12},
              {label:'24小时', value: 24},
              {label:'2天', value: 48},
              {label:'7天', value: 168},
              {label:'15天', value: 360},
              {label:'30天', value: 720},
            ]}
            fieldProps={{
              onChange(value, option) {
                setSearchHour(value);
                setSearchStart(undefined);
                setSearchEnd(undefined);
                formRef.current?.setFieldValue('rangeDate', undefined);
              },
            }}
          />
        </Space>
        
        <Space style={{marginLeft:10}}>
          <ProFormDateTimeRangePicker
            label="时间段"
            name="rangeDate"
            allowClear={true}
            fieldProps={{
              onChange(value, dateString) {
                console.log(value, dateString, dateFormat);
                // setStatDay(value?.format('YYYY-MM-DD'));
                if(!dateString[0] && dateString[0] == ''){
                  setSearchStart(undefined);
                }
                else{
                  setSearchStart(parseInt(`${new Date(dateString[0]).getTime() / 1000}`));
                }

                if(!dateString[1] && dateString[1] == ''){
                  setSearchEnd(undefined);
                }
                else{
                  setSearchEnd(parseInt(`${new Date(dateString[1]).getTime() / 1000}`));
                }
                
                setSearchHour(undefined);
                formRef.current?.setFieldValue('hour', undefined);
              },
            }}
          />
        </Space>        

        <Space style={{marginLeft:10}}>
          <Button
            type="primary"
            key="deleteBatchInst"
            onClick={() => {
              setDataLoading(true);
              setControlState(new Date().getTime());
            }}
          >查询
          </Button>
        </Space>
      </div>

      <div style={{marginTop:-10, marginBottom:20}}>
        <Space><b>地区策略</b>
          <Radio.Group defaultValue="a">
            <Radio
              value="a"
              onClick={() => {
                setSearchAreaPolicy(undefined);
              }}
            >
              全部
            </Radio>
            <Radio
              value="b"
              onClick={() => {
                setSearchAreaPolicy('iran_display');
              }}
            >
              显示: 伊朗
            </Radio>
            <Radio
              value="c"
              onClick={() => {
                setSearchAreaPolicy('iran_hidden');
              }}
            >
              隐藏: 伊朗
            </Radio>
            <Radio
              value="d"
              onClick={() => {
                setSearchAreaPolicy('china_display_only');
              }}
            >
              显示: 仅中国
            </Radio>
          </Radio.Group>
        </Space>

        <Space><b>等级</b>
          <Radio.Group
            key="ckgMemberLevel"
            onChange={(checkedValue) => {
              setSearchMemberLevel(checkedValue.target.value);
              // console.log(checkedValue, checkedValue.target.value);
            }}
            value={searchMemberLevel}
            options={[{ label: '全部', value: -1, key: -1 }].concat(
              c.MemberLevelOptions,
            )}
          ></Radio.Group>
        </Space>

      </div>

      <div>
        <Space>
          <ProFormTreeSelect
            name="groupIds"
            label="分组"
            placeholder="请选择分组"
            // allowClear={false}
            width={1500}
            // secondary
            // rules={[{ required: true, message: '请选择分组' }]}
            request={loadGroupTreeData}
            // tree-select args
            initialValue={searchGroupIds}
            fieldProps={{
              showArrow: true,
              showSearch: true,
              treeCheckable: true,
              // maxTagCount: 1,
              multiple: true,
              treeDefaultExpandAll: true,
              listHeight: 600,
              treeNodeLabelProp: 'title',
              filterTreeNode: (input, option) =>
                option && option.title
                  ? option.title
                      .toString()
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  : false,
              onChange(value, labelList, extra) {
                setSearchGroupIds(value);
              },
            }}
          />
        </Space>
      </div>
        
      </ProForm>

      <Collapse defaultActiveKey={[]} size="small">
        <Panel key='total_flow' header='总流量图'>
          <iframe
            src={`${searchHour ? globalGrafanaModel?.urlGrafanaAllNodeMin.replaceAll('&from=now-24h', '') 
              : searchStart && searchEnd ? globalGrafanaModel?.urlGrafanaAllNodeMin.replaceAll('&from=now-24h&to=now', '')
              : globalGrafanaModel?.urlGrafanaAllNodeMin

            }${searchHour ? `&from=now-${searchHour}h` : ''}${searchStart && searchEnd ? `&from=${searchStart}&to=${searchEnd}` : ''}`}
            width="1500"
            height="250"
            style={{ borderWidth: 0 }}
          ></iframe>
        </Panel>
        <Panel key='total_user_count' header='总在线用户图'>
          <iframe
            src={`${searchHour ? globalGrafanaModel?.urlGrafanaAllUserCountMin.replaceAll('&from=now-24h', '') 
              : searchStart && searchEnd ? globalGrafanaModel?.urlGrafanaAllUserCountMin.replaceAll('&from=now-24h&to=now', '')
              : globalGrafanaModel?.urlGrafanaAllUserCountMin

            }${searchHour ? `&from=now-${searchHour}h` : ''}${searchStart && searchEnd ? `&from=${searchStart}&to=${searchEnd}` : ''}`}
            width="1500"
            height="250"
            style={{ borderWidth: 0 }}
          ></iframe>
        </Panel>
      </Collapse>

      </>}

      extra={<>
        <Space>
          {refreshDataLoading == true ? <Spin />
          :
          <Countdown
            title=""
            key="cdRefresh"
            value={countdownTicks}
            format="s"
            prefix=""
            suffix="秒"
            valueStyle={{
              fontSize: 14,
              color: 'gray',
            }}
            onFinish={reload}
          />
          }
        </Space>
      </>}>
        <CheckCard.Group key="searchGrop">
          {monitorDatas?.map((v) => {
            let bandwidthTotal = (v.bandwidthTotal ?? 0) * 1024 * 1024;
            return <CheckCard
              title={<div style={{width:540}}>
                <div>
                {v.status == true ? <Badge count={<CheckCircleFilled style={{ color: '#52c41a', marginRight: 10 }} />} /> : 
                  v.status == false ? <Badge count={<CloseCircleFilled style={{ color: '#f50', marginRight: 10 }} />} /> : ''}
                
                {v.flag ? <><FlagImage flagName={v.flag} />&nbsp;</> : ''}
                {v.level ? <>{c.getMemberLevelText(v.level)}&nbsp;</> : ''}
                {v.title}
                {v.bandwidthTotal ? <><span style={{color:'orange'}}> {utils.formatRate(bandwidthTotal, true)}</span>
                </> : ''}
                <span style={{color:'#999'}}> [min/max/avg]</span>
                </div>

              </div>}
              value={`${v.id}`}
              style={{width:500}}
              description={<>
              <ChartCard datas={v} />
              </>}
            />
          })}
        </CheckCard.Group>
      </ProCard>


    </PageContainer>
  );
};

export default VpnGroupTreeList;
